<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input v-model="queryInfo.query" placeholder="请输入内容" class="input-with-select" clearable
            @clear='getUsersList'>
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="17">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户表格数据 -->
      <el-table :data="userlist" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username" width="100px" style="text-align: center;"></el-table-column>
        <el-table-column label="邮箱" prop="email" style="text-align: center;"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name" width="100px"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <!-- 开关选项 -->
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949"
              @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot='{row}'>
            <!-- 编辑按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialogVisible(row)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeUserInfo(row.id)"></el-button>
            <el-tooltip content="角色权限" placement="right" effect="light">
              <!-- 角色权限 -->
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="setRolesInfo(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination style="margin-top:15px" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3, 4,5]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户信息 -->
    <el-dialog @close="resetAddForm" title="提示" :visible.sync="addDialogVisible" width="50%">
      <!-- 内容主体 -->
      <el-form ref="addFormRef" label-width="80px" :model="addForm" :rules="addFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户信息 -->
    <el-dialog title="提示" :visible.sync="editDialogVisible" width="50%" @close="resetEditForm">
      <!-- 内容主体 -->
      <el-form ref="editFormRef" label-width="80px" :model="editForm" :rules="addFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditForm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="权限分配" :visible.sync="setDialogVisible" width="30%" @close="selectRoleId=null">
      <!-- 内容主体 -->
      <div>
        <p>用户名：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>分配角色:</p>
        <template>
          <!-- 下啦框 -->
          <el-select v-model="selectRoleId" clearable placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </template>
      </div>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleJurisdiction">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    const validateEmail = function (rule, value, callback) {
      // 邮箱验证规则
      const reg = /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('邮箱不符合格式'))
      }
    }
    const validateMobile = function (rule, value, callback) {
      // 手机验证规则
      const reg = /^1[3456789]\d{9}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('手机号不符合格式'))
      }
    }
    return {
      selectRoleId: '',
      /// 所角色列表
      rolesList: [],
      // 保存正在操作的那个用户的信息
      userInfo: {},
      setDialogVisible: false,
      editDialogVisible: false,
      // 修改用户数据
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 用户信息验证规则
      addFormRules: {
        username: [{
          required: true, message: '请输入用户名', trigger: 'blur'
        },
        {
          min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'
        }
        ],
        password: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'
          }
        ],
        email: [
          {
            required: true, message: '邮箱', trigger: 'blur'
          },
          { validator: validateEmail, rigger: 'blur' }
        ],
        mobile: [
          {
            required: true, message: '请输入手机', trigger: 'blur'
          },
          { validator: validateMobile, rigger: 'blur' }
        ]
      },
      // 用户信息数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户信息框
      addDialogVisible: false,
      // ---------------
      queryInfo: {
        query: '', // 查询参数
        pagenum: 1, // 当前页
        pagesize: 5 // 每页的数据条数
      },
      total: 0, // 分页
      userlist: [] // 渲染表格
    }
  },
  methods: {
    async saveRoleJurisdiction () {
      const { data: res } = this.$http.put(`user/${this.userInfo.id}`, { rid: this.selectRoleId })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      this.setDialogVisible = false
      this.getUsersList()
    },
    async setRolesInfo (row) {
      this.userInfo = row
      this.setDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      this.rolesList = res.data
    },
    removeUserInfo (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`user/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        // 重新加载列表数据
        this.getUsersList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    saveEditForm () {
      // 修改用户信息前的预校验
      this.$refs.editFormRef.validate(async bool => {
        if (!bool) return console.log('校验失败')
        const { data: res } = await this.$http.put(`users/${this.editForm}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.error('修改失败')
      })
      // 修改完成后关闭对话框
      this.editDialogVisible = false
      // 重新获取用户数据列表
      this.getUsersList()
    },
    resetEditForm () {
      this.$refs.editFormRef.resetFields()
    },
    showEditDialogVisible (row) {
      this.editDialogVisible = true
      this.editForm = row
    },
    // 添加用户信息
    saveAddForm () {
      this.$refs.addFormRef.validate(async bool => {
        if (!bool) return console.log('失败')
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        // 添加信息成功后关闭对话框
        this.addDialogVisible = false
        // 重新渲染用户数据列表
        this.getUsersList()
      })
    },
    // 重置进去用户添加框
    resetAddForm () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听用户状态
    async userStateChanged (userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.mate.status !== 200) return this.$$message.error('更新失败')
    },
    // 监听页码值
    handleSizeChange (current) {
      this.queryInfo.pagenum = current
      this.getUsersList()
    },
    handleCurrentChange (size) {
      this.queryInfo.pagesize = size
      this.getUsersList()
    },
    // 用户列表
    async getUsersList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) { return this.$message.error('获取用户列表失败') }
      // 如果返回状态正常，将请求的数据保存在data中
      this.userlist = res.data.users
      this.total = res.data.total
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getUsersList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.el-table {
  margin-top: 15px;
}
</style>
